/**
    @author: dt
    @date: 2025-06-23
    @description: 重复装饰器
*/

using UnityEngine;

namespace DLib.BehaviorTree
{
    /// <summary>
    /// 重复装饰器
    /// 重复执行子节点指定次数
    /// 当repeatCount为-1时，无限重复
    /// </summary>
    public class Repeater : DecoratorNode
    {
        /// <summary>重复次数，-1表示无限重复</summary>
        private int repeatCount;
        
        /// <summary>当前已执行的次数</summary>
        private int currentCount;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="child">要重复执行的子节点</param>
        /// <param name="repeatCount">重复次数，-1表示无限重复</param>
        public Repeater(Node child, int repeatCount = -1) : base(child)
        {
            this.repeatCount = repeatCount;
            this.currentCount = 0;
        }

        /// <summary>
        /// 评估子节点并处理重复逻辑
        /// </summary>
        /// <returns>重复器执行状态</returns>
        protected override NodeState EvaluateChild()
        {
            // 检查是否达到重复次数限制
            if (repeatCount > 0 && currentCount >= repeatCount)
            {
                state = NodeState.Success;
                return state;
            }

            NodeState childState = child.Evaluate();

            switch (childState)
            {
                case NodeState.Success:
                    // 子节点成功，增加计数
                    currentCount++;
                    if (repeatCount > 0 && currentCount >= repeatCount)
                    {
                        // 达到重复次数，重复器成功
                        state = NodeState.Success;
                    }
                    else
                    {
                        // 继续重复，重复器运行中
                        state = NodeState.Running;
                    }
                    break;
                case NodeState.Failure:
                    // 子节点失败，重复器失败
                    state = NodeState.Failure;
                    break;
                case NodeState.Running:
                    // 子节点运行中，重复器运行中
                    state = NodeState.Running;
                    break;
            }

            return state;
        }

        /// <summary>
        /// 重置重复器状态
        /// 将当前计数重置为0
        /// </summary>
        public override void Reset()
        {
            currentCount = 0;
        }
    }
} 